﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TomcatTool
{
    class Program
    {
        static Catalina catalina = null;
        static void Main(string[] args)
        {
            try
            {
                Console.Title = "tomcat-Tool";
                SetConsoleCtrlHandler(cancelHandler, true);
                catalina = new Catalina();
                string path = System.Environment.CurrentDirectory;
                Console.WriteLine("Current Path: " + path);
                Thread th = new Thread(new ThreadStart(() =>
                {
                    catalina.Run(path);// @"E:\Tools\DevTools\apache-tomcat-9.0.29\bin");
                }));
                th.Start();
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                if (catalina != null)
                    catalina.Close();
            }
            Console.ReadLine();
        }

        public delegate bool ControlCtrlDelegate(int CtrlType);
        [DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);
        private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);

        public static bool HandlerRoutine(int CtrlType)
        {
            switch (CtrlType)
            {
                case 0:
                    Console.WriteLine("0工具被强制关闭"); //Ctrl+C关闭  
                    break;
                case 2:
                    Console.WriteLine("2工具被强制关闭");//按控制台关闭按钮关闭  
                    break;
            }
            if (catalina != null)
                catalina.Close();
            return false;
        }

    }
}
